package cn.b.sky.flowable.controller;

import cn.b.sky.flowable.cmd.HistoryProcessInstanceDiagramCmd;
import cn.b.sky.flowable.constans.GlobalDefine;
import cn.b.sky.flowable.model.NodeDTO;
import cn.b.sky.flowable.model.WorkFlowHistory;
import cn.b.sky.flowable.model.condition.WaitTaskCondition;
import cn.b.sky.flowable.service.WorkFlowFacade;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.form.constans.CustomerPageConstans;
import cn.b.sky.form.model.*;
import cn.b.sky.form.service.*;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.user.service.UserService;
import cn.b.sky.user.service.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;

@Controller
@RequestMapping(value = "/workflow/*")
@Slf4j
public class ActivitiController extends SecurityController {

  @Resource
  private WorkFlowFacade workFlowFacade;

  @Resource
  private UserService userService;
  //业务数据map
  private Map<String, Object> operationMap;

  //流程数据map
  private Map<String, Object> flowMap;
  
  @Resource
  private BusinessFieldService businessFieldService;

  @Resource
  private BusinessTypeService businessTypeService;
  @Resource
  private BusinessAttachmentService businessAttachmentService;
  @Resource
  private ScreenService screenService;
  
  @Resource
  private FormObjectService formObjectService;
  
  private final Map<String, Map<String, Object>> dataMap = new HashMap<String, Map<String, Object>>();

  /**
   * 
   * <strong>Title : waitTaskList<br></strong>
   * <strong>Description : </strong>待办<br> 
   * <strong>Create on : 2015-11-24 下午12:53:08<br></strong>
   * <p>
   * @param page
   * @param navTabId
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("waitTaskList")
  public String waitTaskList(WaitTaskCondition page, String navTabId, Model model) {
    
    model.addAttribute("page", this.workFlowFacade.findTasks(SecurityContextUtil.getCurrentUserName(), this.getSiteCode(), page));
    model.addAttribute(NAVTABID, navTabId);
    return "workflow/waittask_list";
  }

  /**
   * <strong>Title : finishedTaskList<br></strong>
   * <strong>Description : </strong>已办<br> 
   * <strong>Create on : 2015-11-24 下午12:53:16<br></strong>
   * <p>
   * @param page
   * @param navTabId
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("finishedTaskList")
  public String finishedTaskList(WaitTaskCondition page, String navTabId, Model model) {
    this.workFlowFacade.findfinishedTasks(SecurityContextUtil.getCurrentUserName(), this.getSiteCode(), page);
    model.addAttribute("page", page);
    model.addAttribute(NAVTABID, navTabId);
    return "workflow/finishedtask_list";
  }

  /**
   * 
   * <strong>Title : runningTaskList<br></strong>
   * <strong>Description : </strong>运行中的实例 
   * <strong>Create on : 2015-11-24 下午1:22:12<br></strong>
   * <p>
   * @param page
   * @param navTabId
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("runningTaskList")
  public String runningTaskList(WaitTaskCondition page, String navTabId, Model model) {
    this.workFlowFacade.findRunningTasks(this.getSiteCode(), page);
    model.addAttribute("page", page);
    model.addAttribute(NAVTABID, navTabId);
    return "workflow/runningtask_list";
  }

  /**
   * 
   * <strong>Title : startWorkflow<br></strong>
   * <strong>Description : </strong>启动流程，统一入口，这里不支持业务数据处理，
   * 如果需要处理业务数据，则需要自己另写启动流程的方法<br> 
   * <strong>Create on : 2015-11-6 下午3:55:41<br></strong>
   * <p>
   * @param navTabId 窗体id
   * @return
   * DWZResult
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "startTask")
  @ResponseBody
  public DWZResult startWorkflow(String navTabId, HttpServletRequest request) {

    try {
      fillOprationMapAndFlowMap(request);
      //设置发起人
      this.operationMap.put(GlobalDefine.WorkFlow.HANDLEUSERCODE, SecurityContextUtil.getCurrentUserName());
      this.operationMap.put(GlobalDefine.WorkFlow.HANDLEUSERTEXT, SecurityContextUtil.getCurrentUserText());
      this.operationMap.put(GlobalDefine.WorkFlow.CUREENTSITECODE, this.getSiteCode());
      //设置流程业务key
      ProcessInstance processInstance = workFlowFacade.startProcess(this.getMap());
      return dialogAjaxDone("流程已启动，流程ID：" + processInstance.getId(), navTabId, null, null, null);
    } catch (FlowableException e) {
      if (e.getMessage().indexOf("no processes deployed with key") != -1) {
        log.warn("没有部署流程!", e);
        return ajaxError("没有部署流程，请在[工作流]->[流程管理]页面点击<重新部署流程>"); 
      } else if (e.getCause().getCause().getCause() instanceof ImeException) {
        ImeException ie = (ImeException) e.getCause().getCause().getCause();
        return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), ie.getErrorCode()));
      } else {
        log.error("启动请假流程失败：", e);
        return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOperation.M"));
      }
    }catch(ImeException e){
      log.error("启动请假流程失败：", e);
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), e.getErrorCode()));
    }catch (Exception e) {
      log.error("启动请假流程失败：", e);
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOperation.M"));
    }
  }
  /**
   * 签收任务
   */
  @RequestMapping(value = "claimTask")
  @ResponseBody
  public DWZResult claim(String taskId, String navTabId) {

    String userId = SecurityContextUtil.getCurrentUserName();
    workFlowFacade.claimTask(taskId, userId, this.getSiteCode());

    return navTabAjaxDone(navTabId, null, null, null, null, null);
  }

  /**
   *  处理任务
   *  点击处理按钮触发处理任务
   */
  @RequestMapping(value = "handleTask")
  public String handleTask(String taskId, String navTabId, Model model) {
    if (StringUtils.isBlank(taskId)) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }

    Task task = workFlowFacade.getTaskById(taskId);
    if (task == null || StringUtils.isBlank(task.getId())) {
      throw ImeException.newException("workFlowNoForm.M");
    }
    ProcessInstance processInstance = workFlowFacade.getProcessInstanceById(task.getProcessInstanceId());
    String bussinessKey = processInstance.getBusinessKey();
    //获取下一节点的处理表单
    String redirect = task.getFormKey();
    if (StringUtils.isBlank(redirect)) {
      redirect = workFlowFacade.getTaskFormKey(processInstance.getDeploymentId(),
          task.getTaskDefinitionKey(), this.getSiteCode());
    }
    if (StringUtils.isBlank(redirect)) {
      throw ImeException.newException("workFlowNoForm.M");
    }
    String formKey = null;
    //如果是url 则表示自定义表单，custombutton表示是否用自己定义的按钮
    if(redirect.indexOf("/") != -1){
      if (redirect.indexOf("?") != -1) {
        redirect = redirect.replaceAll("\\s*", ""); //去掉空格
        String[] str = redirect.split("[?&]");

        if (str.length == 2) {
          String button = str[1];
          model.addAttribute(GlobalDefine.WorkFlow.FORMKEY_CUSTOMBUTTON, button.replaceAll("custombutton=", ""));
        }
        formKey = redirect + "&navTabId=" + navTabId + "&bussinessKey=" + bussinessKey;
      } else {
        formKey = redirect + "?navTabId=" + navTabId + "&bussinessKey=" + bussinessKey;
      }
    }else{
      //不然就是系统配置的表单,pageController里的获取表单值
      formKey =  "/workflow/getFrom/" + redirect + "/" + bussinessKey;
    }
    
    //审批历史
    List<WorkFlowHistory> historys = workFlowFacade.getWorkFlowHistoryByBusinessKeyAndTaskDefKey(bussinessKey, null,
        this.getSiteCode());

    model.addAttribute("historys", historys);
    model.addAttribute(GlobalDefine.WorkFlow.FORMKEY, formKey);
    model.addAttribute(GlobalDefine.WorkFlow.TASK_ID, taskId);
    model.addAttribute(GlobalDefine.WorkFlow.BUSINESSKEY, bussinessKey);
    return "workflow/handle_task";
  }

  /**
   * 完成任务
   *
   * @param taskId
   * @return
   * 
   * */
  @RequestMapping(value = "completeTask", method = { RequestMethod.POST, RequestMethod.GET })
  @ResponseBody
  public DWZResult completeTask(String taskId, String bussinessKey, String navTabId, HttpServletRequest request) {
    if (StringUtils.isBlank(taskId)) {
      return ajaxError(SystemConstant.PARAMETERNULL);
    }
    try {
      fillOprationMapAndFlowMap(request);
      //设置完成人
      this.operationMap.put(GlobalDefine.WorkFlow.HANDLEUSERCODE, SecurityContextUtil.getCurrentUserName());
      this.operationMap.put(GlobalDefine.WorkFlow.HANDLEUSERTEXT, SecurityContextUtil.getCurrentUserText());
      this.operationMap.put(GlobalDefine.WorkFlow.CUREENTSITECODE, this.getSiteCode());
      workFlowFacade.completeTask(taskId, changeMap(flowMap), changeMap(operationMap));
      return dialogAjaxDone(navTabId, null, null, null);
    } catch (FlowableException e) {
      log.error("error on complete task {" + taskId + "}, variables={}", e);
      //抛出监听器里抛出来的ImeException,activit包了三层，ActivitiException， ELException，ImeException 
      if (e.getCause().getCause().getCause() instanceof ImeException) {
        ImeException ie = (ImeException) e.getCause().getCause().getCause();
        return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), ie.getErrorCode()));
      }
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOperation.M"));
    } catch (Exception e) {
      log.error("error on complete task {" + taskId + "}, variables={}", e);
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOperation.M"));
    }
  }

  @RequestMapping(value = "endWorkFlow")
  @ResponseBody
  public DWZResult endWorkFlow(String taskId, String processInstanceId, String navTabId, Model model) {
    if (StringUtils.isBlank(processInstanceId)) {
      if (!StringUtils.isBlank(taskId)) {
        Task task = workFlowFacade.getTaskById(taskId);
        processInstanceId = task.getProcessInstanceId();
      } else {
        return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
      }
    }
    workFlowFacade.endWorkFlow(processInstanceId);
    return navTabAjaxDone(navTabId, null, null, null, null, null);
  }

  /**
   * 
   * <strong>Title : transferAssignee<br></strong>
   * <strong>Description : </strong>移交<br> 
   * <strong>Create on : 2015-11-25 上午10:25:55<br></strong>
   * <p>
   * @param taskId
   * @param userCode
   * @param navTabId
   * @param model
   * @return
   * DWZResult
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "transferAssignee")
  @ResponseBody
  public DWZResult transferAssignee(String taskId, String userCode, String navTabId, Model model) {
    UserInfo user = userService.selectUser(this.getSiteCode(), userCode);
    workFlowFacade.transferAssignee(taskId, userCode);
    WorkFlowHistory history = new WorkFlowHistory();
    history.setUserCode(SecurityContextUtil.getCurrentUserName());
    history.setUserText(SecurityContextUtil.getCurrentUserText());
    Task task = workFlowFacade.getTaskById(taskId);
    //移交
    workFlowFacade.saveWorkFlowHistory(task, history, user.getUsername());
    return dialogAjaxDone(navTabId, null, null, null);
  }

  /**
   * 
   * <strong>Title : showProcessImg<br></strong>
   * <strong>Description : </strong>流程监控，查看流程图<br> 
   * <strong>Create on : 2015-11-10 下午2:40:16<br></strong>
   * <p>
   * @param processInstanceId
   * @param model
   * @return
   * @
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "showProcessImg")
  public String showProcessImg(String taskId, String processInstanceId, Model model) {
    if (StringUtils.isBlank(processInstanceId)) {
      if (!StringUtils.isBlank(taskId)) {
        Task task = workFlowFacade.getTaskById(taskId);
        if (task == null || StringUtils.isBlank(task.getId())) {
          HistoricTaskInstance historicTask = workFlowFacade.getHistoricTaskById(taskId);
          processInstanceId = historicTask.getProcessInstanceId();
        } else {
          processInstanceId = task.getProcessInstanceId();
        }
      } else {
        throw ImeException.newException(SystemConstant.PARAMETERNULL);
      }
    }
    model.addAttribute("processInstanceId", processInstanceId);
    List<NodeDTO> noteDto = workFlowFacade.traceProcess(processInstanceId);
    List<WorkFlowHistory> historys = workFlowFacade.getWorkFlowHistoryByprocessInstanceId(processInstanceId,
        this.getSiteCode());
    model.addAttribute("workFlowHistorys", historys);
    model.addAttribute("nodeDto", noteDto);
    return "workflow/processImg_show";
  }

  /**
   * 
   * <strong>Title : showBusinessImg<br></strong>
   * <strong>Description : </strong>业务数据查看流程历史记录的url<br> 
   * <strong>Create on : 2015-12-2 下午3:47:11<br></strong>
   * <p>
   * @param businessKey
   * @param model
   * @return
   * @
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "showBusinessImg")
  public String showBusinessImg(String businessKey, Model model) {
    if (!StringUtils.isBlank(businessKey)) {
      HistoricProcessInstance historicProcessInstance = workFlowFacade
          .getHistoricProcessInstanceByBusinessKeyAndTenantId(businessKey, this.getSiteCode());
      String processInstanceId = historicProcessInstance.getId();
      model.addAttribute("processInstanceId", historicProcessInstance.getId());
      List<NodeDTO> noteDto = workFlowFacade.traceProcess(processInstanceId);
      List<WorkFlowHistory> historys = workFlowFacade.getWorkFlowHistoryByprocessInstanceId(processInstanceId,
          this.getSiteCode());
      model.addAttribute("workFlowHistorys", historys);
      model.addAttribute("nodeDto", noteDto);
    }
    return "workflow/processImg_show";
  }

  /**
   * 
   * <strong>Title : loadByProcessInstance<br></strong>
   * <strong>Description : </strong>获取运行中的流程实例的流程图，监控和查看历史时使用<br> 
   * <strong>Create on : 2015-11-3 下午3:26:54<br></strong>
   * <p>
   * @param resourceType
   * @param processInstanceId
   * @param response
   * @
   * void
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   * @throws IOException 
   */
  @RequestMapping(value = "/resource/process-instance")
  public void loadByProcessInstance(@RequestParam("type") String resourceType,
      @RequestParam("pid") String processInstanceId, HttpServletResponse response) throws IOException {
    Command<InputStream> cmd = new HistoryProcessInstanceDiagramCmd(processInstanceId);

    InputStream is = workFlowFacade.executeCommand(cmd);
    response.setContentType("image/png");

    int len = 0;
    byte[] b = new byte[1024];

    while ((len = is.read(b, 0, 1024)) != -1) {
      response.getOutputStream().write(b, 0, len);
    }
  }
  /**
   * 
   * <strong>Title : getStartWorkFlowForm<br></strong>
   * <strong>Description : </strong>流程启动弹出表单，只针对系统界面配置的表单<br> 
   * <strong>Create on : 2016-11-22 下午5:45:25<br></strong>
   * <p>
   * @param model
   * @param processdefinitionId
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("/startWorkFlow/{processdefinitionId}")
  public String getStartWorkFlowForm(Model model,
      @PathVariable("processdefinitionId")String processdefinitionId) {  
    //启动界面，查询开始节点关联的表单
    ProcessDefinition pd = workFlowFacade
        .getProcessDefinitionByProcessDefinitionKey(processdefinitionId, this.getSiteCode());
    //表单渲染
    String startFormKey = workFlowFacade.getStartNodeFormKey(pd.getDeploymentId(), this.getSiteCode());
    if(StringUtils.isBlank(startFormKey)){
      throw ImeException.newException("没有流程表单，不可以直接启动流程!");
    }
    //查询此form的元素
    Screen screen = screenService.getScreen(this.getSiteCode(), startFormKey);
    setBusinessFiledAndValueToScreen(screen);
    BusinessType type = businessTypeService.getBusinessTypeAndFields(this.getSiteCode(), screen.getBusinessType());
    if (type == null || type.getTableCreateFlag() != 1) {
      throw ImeException.newException("数据库表不存在");
    }
    //放到model里进行数据处理
    model.addAttribute(CustomerPageConstans.SCREEN_PARAM, screen);
    //流程自定义表单key
    model.addAttribute(CustomerPageConstans.FORMKEY, startFormKey);
    //流程key
    model.addAttribute(CustomerPageConstans.PROCESSDEFINITIONID, processdefinitionId);
    return "workflow/startFlowForm";
  }
  
  /**
   * 
   * <strong>Title : getCommonForm<br></strong>
   * <strong>Description : 获取用户配置的表单</strong><br> 
   * <strong>Create on : 2016-11-9 下午7:37:02<br></strong>
   * <p>
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("/getFrom/{formKey}/{bussinessKey}")
  public String getCommonForm(Model model, @PathVariable("formKey") String formKey,
                              @PathVariable("bussinessKey") String bussinessKey) {
    //查询此form的元素
    Screen screen = screenService.getScreen(this.getSiteCode(), formKey);
    setBusinessFiledAndValueToScreen(screen);
    BusinessType type = businessTypeService.getBusinessTypeAndFields(this.getSiteCode(), screen.getBusinessType());
    if (type == null || type.getTableCreateFlag() != 1) {
      throw ImeException.newException("数据库表不存在");
    }
    //通过业务模型查询业务数据
    if (!StringUtils.isBlank(bussinessKey)) {
      List<Map<String, Object>> list = formObjectService.getFormObjectDataByBizId(this.getSiteCode(),
          type.getDbTable(), bussinessKey);
      if (list != null && list.size() > 0) {
        if (list.size() != 1) {
          throw ImeException.newException("查询数据多余一条");
        }
        Map<String, Object> map = list.get(0);
        setBusinessFieldValue(map, screen.getSections());
      }
    }
    //放到model里进行数据处理
    model.addAttribute(CustomerPageConstans.SCREEN_PARAM, screen);
    //业务key要传到后面业务数据修改使用
    model.addAttribute(CustomerPageConstans.BUSINESSCODE, bussinessKey);
    return "workflow/activitiForm";
  }

  private void setBusinessFiledAndValueToScreen(Screen screen) {
    List<Section> sections = screen.getSections();
    
    if(sections != null && sections.size() > 0){
      for(Section section : sections){
        List<ScreenField> screenFields = section.getScreenField();
        setBusinessFiledAndValueToScreenField(screenFields);
      }
    }
    
  }

  private void setBusinessFiledAndValueToScreenField(List<ScreenField> screenFields) {
    if(screenFields != null && screenFields.size() > 0){
      for(ScreenField field : screenFields){
        //有可能为空，占位符，如果是占位符就不管了业务字段
        if(!StringUtils.isBlank(field.getBusinessField())){
          field.setBf(businessFieldService.getBusinessFieldAndValues(
              field.getSiteCode(), field.getBusinessType(), field.getBusinessField()));
        }else{
          //构造一个占位符的业务字段，虚拟的,为了满足占位符的设计，头大
          field.setBf(getPlaceholderBusinessFiled());
        }
      }
    }
    
  }


  /**
   * 
   * <strong>Title : getPlaceholderBusinessFiled<br></strong>
   * <strong>Description : </strong>获取空的占位符<br> 
   * <strong>Create on : 2016-11-18 下午2:46:07<br></strong>
   * <p>
   * @return
   * BusinessField
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private BusinessField getPlaceholderBusinessFiled() {
    BusinessField bf = new BusinessField();
    bf.setFieldType("placeholder");
    return bf;
  }


  /**
   * 
   * <strong>Title : setBusinessFieldValue<br></strong>
   * <strong>Description : </strong>给字段属性赋值<br> 
   * <strong>Create on : 2016-11-15 上午9:20:38<br></strong>
   * <p>
   * @param map
   * @param sections
   * void
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private void setBusinessFieldValue(Map<String, Object> map, List<Section> sections) {
    if (sections != null) {
      for (Section section : sections) {
        List<ScreenField> screenFields = section.getScreenField();
        if (screenFields != null && screenFields.size() > 0) {
          for (ScreenField field : screenFields) {
            BusinessField bf = field.getBf();
            if (bf != null && !StringUtils.isBlank(bf.getDbField())) {
              //附件获取填充      
                bf.setDefaultValue(convertData(bf.getDataType(), map.get(bf.getDbField().toUpperCase())));
                if("attachment".equalsIgnoreCase(bf.getFieldType())){
                  //附件数量大于0的去获取下附件
                  if(!StringUtils.isBlank(bf.getDefaultValue()) || !"0".equals(bf.getDefaultValue())){
                    bf.setAttachments(businessAttachmentService.getBusinessAttachments(
                        new BusinessAttachment(Long.valueOf(map.get(CustomerPageConstans.ID).toString()),
                            this.getSiteCode(), bf.getBusinessType(), bf.getBusinessField())));
                  }
                }
            }
          }
        }
      }
    }

  }

  /**
   * 
   * <strong>Title : convertData<br></strong>
   * <strong>Description : 获取转换后的数据类型目前之处理日期类型，
   * 不考虑那么多，后面新数据类型出来再说</strong><br> 
   * <strong>Create on : 2016-11-15 上午9:37:43<br></strong>
   * <p>
   * @param dataType
   * @param value
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private String convertData(String dataType, Object value) {
    if(value != null){
      if("date".equalsIgnoreCase(dataType)){
        return DateUtils.getDateUtils(DateUtils.YYYY_MM_DD).format(value);
      }else if("datetime".equalsIgnoreCase(dataType)){
        return DateUtils.getDateUtils().format(value);
      }else{
        return value.toString();
      }
    }
    return "";
  }

  /**
   * 流程变量按照标准flowMap+"_"+变量名，不然不当做流程变量
   */
  private void fillOprationMapAndFlowMap(HttpServletRequest request) {
    flowMap = new HashMap<String, Object>();
    operationMap = new HashMap<String, Object>();
    if (flowMap != null && operationMap != null) {
      Map<String, String[]> map = request.getParameterMap();
      Set<Entry<String, String[]>> set = map.entrySet();
      Iterator<Entry<String, String[]>> iterator = set.iterator();
      while (iterator.hasNext()) {
        Entry<String, String[]> entry = iterator.next();
        String key = entry.getKey();
        Object paramenter = request.getParameterValues(key);
        if (key.indexOf(GlobalDefine.WorkFlow.WORKFLOWMAP) == -1) {
          operationMap.put(entry.getKey(), paramenter);
        } else {
          if (key.indexOf("_") != -1) {
            String[] flowKey = key.split("_");
            if (flowKey.length == 2) {
              flowMap.put(flowKey[1], paramenter);
            }
          }
        }
      }
    }
  }

  private Map<String, Object> changeMap(Map<String, Object> map) {
    Set<Entry<String, Object>> mapToSet = map.entrySet();
    Iterator<Entry<String, Object>> iterator = mapToSet.iterator();
    while (iterator.hasNext()) {
      Entry<String, Object> entry = iterator.next();
      Object object = entry.getValue();
      if (object instanceof String[] && ((String[]) object).length == 1) {
        map.put(entry.getKey(), ((String[]) object)[0]);
      }
    }
    return map;
  }

  private Map<String, Map<String, Object>> getMap() {
    dataMap.put(GlobalDefine.WorkFlow.OPERATIONMAP, this.changeMap(operationMap));
    dataMap.put(GlobalDefine.WorkFlow.WORKFLOWMAP, this.changeMap(flowMap));
    return dataMap;
  }
}
